package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.constant.TableFieldConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.utils.ResultUtil;
import com.sky.vo.SetmealVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * ClassName: SetmealServiceImpl
 * Description:
 *
 * @Author: Jdz
 * @Create: 2024/1/25 - 15:56
 */
@Service
@RequiredArgsConstructor
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    private final SetmealDishService setmealDishService;
    private final SetmealMapper setmealMapper;

    @Transactional
    @Override
    public Result saveWithDish(SetmealDTO setmealDTO) {
        //向套餐表插入数据
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        boolean r1 = super.save(setmeal);
        Long setmealId = setmeal.getId();
        //保存套餐和菜品的关联关系
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(s -> s.setSetmealId(setmealId));
        boolean r2 = setmealDishService.saveBatch(setmealDishes);
        return ResultUtil.getResult(r1 && r2);
    }

    @Override
    public Result<PageResult> pageQuery(SetmealPageQueryDTO pageQueryDTO) {
        int page = pageQueryDTO.getPage();
        int pageSize = pageQueryDTO.getPageSize();
        String name = pageQueryDTO.getName();
        Integer categoryId = pageQueryDTO.getCategoryId();
        Integer status = pageQueryDTO.getStatus();
        Page<SetmealVO> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = Wrappers.<Setmeal>query()
                .eq(ObjUtil.isNotNull(status), TableFieldConstant.SETMEAL_TATUS, status)
                .like(StrUtil.isNotBlank(name), TableFieldConstant.SETMEAL_NAME, name)
                .lambda()
                .eq(ObjUtil.isNotNull(categoryId), Setmeal::getCategoryId, categoryId)
                .orderByAsc(Setmeal::getCreateTime);
        Page<SetmealVO> setmealVOPage = setmealMapper.pageQuery(pageParam, wrapper);
        return Result.success(new PageResult(setmealVOPage.getTotal(), setmealVOPage.getRecords()));
    }

    @Transactional
    @Override
    public Result deleteBatch(List<Long> ids) {
        // 若包含起售套餐则删除不了
        ids.forEach(id-> {
            Setmeal setmeal = super.getById(id);
            if (Objects.equals(setmeal.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });
        // 删除套餐表中的数据
        boolean r1 = super.removeBatchByIds(ids);
        //删除套餐菜品关系表中的数据
        boolean r2 = setmealDishService.remove(Wrappers.<SetmealDish>lambdaQuery()
                .in(SetmealDish::getSetmealId, ids));
        return ResultUtil.getResult(r1 && r2);
    }

    @Override
    public Result startOrStop(Integer status, Long id) {
        boolean res = super.updateById(Setmeal.builder().status(status).id(id).build());
        return ResultUtil.getResult(res);
    }

    @Override
    public Result<SetmealVO> getByIdWithDish(Long id) {
        Setmeal setmeal = super.getById(id);
        // 操作setmeal_dish表
        List<SetmealDish> setmealDishes = setmealDishService.list(Wrappers.<SetmealDish>lambdaQuery()
                .in(SetmealDish::getSetmealId, id));
        SetmealVO setmealVO = BeanUtil.copyProperties(setmeal, SetmealVO.class);
        setmealVO.setSetmealDishes(setmealDishes);
        return Result.success(setmealVO);
    }

    @Override
    public Result update(SetmealDTO setmealDTO) {
        Setmeal setmeal = BeanUtil.copyProperties(setmealDTO, Setmeal.class);
        //1、修改套餐表，执行update
        boolean r1 = super.updateById(setmeal);
        //套餐id
        Long setmealId = setmealDTO.getId();
        //2、删除套餐和菜品的关联关系，操作setmeal_dish表，执行delete
        boolean r2 = setmealDishService.remove(Wrappers.<SetmealDish>lambdaQuery()
                .eq(SetmealDish::getSetmealId, setmealId));
        List<SetmealDish> setmealDishes = setmealDishService.list();
        if (setmealDishes != null && setmealDishes.size() > 0) {
            setmealDishes.forEach(sd -> sd.setSetmealId(setmealId));
            boolean batchService = setmealDishService.saveOrUpdateBatch(setmealDishes);
            return ResultUtil.getResult(r1 && batchService);
        } else {
            return ResultUtil.getResult(r1);
        }
    }
}
